import EventBus from './EventBus.js'
import utils from './utils.js'

var ws;
var wsUrl = "ws://10.36.108.26:9999/im";

//初始化websocket
function initWs(){
	ws = new WebSocket(wsUrl);
	ws.onopen = () => {
		console.log("成功连接服务器...");
		//发送一个注册消息 告诉服务器，当前的Channel是谁
		var msgObj = {
			action: 100,
			content: utils.getUser().id
		}
		
		//发送给服务器
		sendMsg(msgObj);
	}
	
	ws.onclose = () => {
		console.log("断开了服务器的连接...");
	}
	
	ws.onmessage = serverMessage;
}

//接收服务器消息的方法
function serverMessage(msg) {
	console.log("接收到服务器的消息：", msg.data);
	var msgObj = JSON.parse(msg.data);
	//处理不同的消息
	switch(msgObj.action) {
		case 101:
		//收到一个单聊的消息 - 回复给服务器一个确认消息
		var resObj = {
			action: 102,
			from: utils.getUser().id,
			content: msgObj.id
		}
		sendMsg(resObj);
		
		//将消息展示的当前用户的聊天页面上
		EventBus.$emit("reciMsg", msgObj);
		
		break;
	}
}

//发送消息给服务器
function sendMsg(msgObj){
	ws.send(JSON.stringify(msgObj));
}



//关闭wesbcoekt连接
function close(){
	if(ws){
		ws.close();
	}
}


export default {
	initWs,
	close,
	sendMsg
}